package com.chinacache.maint.workorder.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.chinacache.maint.commons.orm.hibernate.Page;
import com.chinacache.maint.commons.web.struts2.CRUDActionSupport;
import com.chinacache.maint.workorder.entity.Field;
import com.chinacache.maint.workorder.entity.FieldAttribute;
import com.chinacache.maint.workorder.service.FieldAttributeManager;
import com.chinacache.maint.workorder.service.FieldManager;

@SuppressWarnings("serial")
public class FieldAction extends CRUDActionSupport<Field> {
	private FieldManager fieldManager;
	private FieldAttributeManager fieldAttributeManager;
	private Field entity;
	private Integer id;
	private Page<Field> page = new Page<Field>();
	private Map<String, List> view = null;

	public void setFieldAttributeManager(
			FieldAttributeManager fieldAttributeManager) {
		this.fieldAttributeManager = fieldAttributeManager;
	}

	@Override
	public String delete() throws Exception {
		fieldManager.deleteField(id);
		return RELOAD;
	}

	@Override
	public Field getModel() {
		return entity;
	}

	@Override
	public Page<Field> getPage() {
		return page;
	}

	@Override
	public String list() throws Exception {
		page = fieldManager.getAllField(page);
		return SUCCESS;
	}

	@Override
	public void prepare() throws Exception {
		if (id != null) {
			entity = fieldManager.getField(id);
		} else {
			entity = new Field();
		}
	}

	@Override
	public String save() throws Exception {
		fieldManager.saveField(entity);
		return RELOAD;
	}

	public void setFieldManager(FieldManager fieldManager) {
		this.fieldManager = fieldManager;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String view() throws Exception {
		List<List> fasList = new ArrayList<List>();
		view = new HashMap<String, List>();
		Set<FieldAttribute> faSet = entity.getFieldAttibutes();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (FieldAttribute fa : faSet) {
			if (!groupIds.contains(fa.getGroupId())) {
				groupIds.add(fa.getGroupId());
			}
		}
		for (Integer groupId : groupIds) {
			List faByGroupIdList = fieldAttributeManager
					.getFieldAttributeByGroupId(groupId);
			fasList.add(faByGroupIdList);

		}
		view.put(entity.getName(), fasList);
		return "view";
	}

	public Map<String, List> getView() {
		return view;
	}

	public void setView(Map<String, List> view) {
		this.view = view;
	}

}
